<template>
	<div>
		<div class="container">
			<div class="handle-box">
				<el-select v-model="query.status" placeholder="账号级别" class="handle-select mr10" clearable>
					<el-option :key="index" :label="item" :value="index" v-for="(item, index) in statusList"></el-option>
				</el-select>
				<el-input v-model="query.name" placeholder="用户名" class="handle-input mr10"></el-input>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" :icon="Plus" @click="showAdd('add')">新增</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
				v-loading="tableLoading">
				<el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
				<el-table-column prop="username" label="用户名"></el-table-column>
				<el-table-column label="用户昵称" prop="nickname"></el-table-column>
				<el-table-column label="头像" align="center">
					<template #default="scope">
						<el-image class="table-td-thumb" :src="`/src/assets/img/user/${scope.row.image}.webp`" :z-index="10"
							:preview-src-list="[`/src/assets/img/user/${scope.row.image}.webp`]" preview-teleported>
						</el-image>
					</template>
				</el-table-column>
				<el-table-column label="用户等级" align="center">
					<template #default="scope">
						<el-tag class="ml-2" v-if="scope.row.status === 2">超级管理员</el-tag>
						<el-tag class="ml-2" type="success" v-else-if="scope.row.status === 1">管理员</el-tag>
						<el-tag class="ml-2" type="info" v-else-if="scope.row.status === 0">普通用户</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						<el-button text :icon="Edit" @click="showAdd('edit', scope.row)" v-permiss="4">
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" @click="handleDelete(scope.row)" v-permiss="4">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
					:page-size="query.pageSize" :total="query.total" @current-change="handlePageChange"></el-pagination>
			</div>
		</div>
		<!-- 新增/编辑弹出框 -->
		<el-dialog :title="addForm.title + '用户'" v-model="addVisible" width="50%" align-center
			@close="() => { addRef.resetFields() }">
			<el-form label-position="left" label-width="80px" v-loading="addLoading" :rules="addRules" :model="addForm"
				ref="addRef">
				<el-form-item label="ID" prop="id" v-if="addForm.title === '编辑'">
					<el-input v-model="addForm.id" placeholder="ID" :disabled="addForm.title === '编辑'"></el-input>
				</el-form-item>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addForm.username" placeholder="用户名"></el-input>
				</el-form-item>
				<el-form-item label="用户密码" prop="password" :key="addForm.title">
					<el-input v-model="addForm.password" placeholder="用户密码"></el-input>
				</el-form-item>
				<el-form-item label="用户等级" prop="status">
					<el-select v-model="addForm.status" placeholder="用户等级" class="handle-select mr10">
						<el-option :key="index" :label="item" :value="index"
							v-for="(item, index) in statusList"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="用户昵称" prop="nickname">
					<el-input v-model="addForm.nickname"></el-input>
				</el-form-item>
				<el-form-item label="用户头像" prop="image">
					<el-select v-model="addForm.image" placeholder="用户头像" class="handle-select mr10">
						<el-option :key="index" :label="item" :value="item" v-for="(item, index) in 8">
							<el-image style="float: left;width: 30px; height: 30px" class="table-td-thumb"
								:src="`/src/assets/img/user/${item}.webp`" :z-index="10" preview-teleported>
							</el-image>
							<span style="float: right;font-size: 13px;">{{ item }}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeAdd(addRef)">取 消</el-button>
					<el-button type="primary" @click="submitAdd(addRef)">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="userManage">
import { reactive, ref } from "vue";
import { Delete, Edit, Search, Plus } from '@element-plus/icons-vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { page, addUser, updateUser,deleteUser } from '../api/user'

const statusList = ['普通用户', '管理员用户', '超级管理员用户']
const query = reactive({
	status: '',
	name: '',
	pageIndex: 1,
	pageSize: 8,
	total: 0,
	limit: 8
})
const tableLoading = ref(false);
const tableData = ref([])
// 获取数据
const getData = () => {
	tableLoading.value = true
	const params = {
		status: query.status,
		name: query.name,
		page: query.pageIndex,
		limit: query.limit
	}
	page(params).then((res: any) => {
		if (res.code !== 200) return ElMessage.error(res.msg || '获取用户列表失败')
		const { data } = res;
		query.total = data.total;
		tableData.value = data.data
	}).finally(() => tableLoading.value = false)
}
getData();
// 点击搜索
const handleSearch = () => {
	getData();
}
// 展示添加用户框
const showAdd = (str: string, row?: any) => {
	if (str === 'edit') {
		addForm.title = "编辑";
		addForm.id = row.id;
		addForm.username = row.username;
		addForm.nickname = row.nickname;
		addForm.status = row.status;
		addForm.image = row.image;
		addRules.password = []

	} else {
		addForm.title = "新增";
		addForm.id = '';
		addForm.username = '';
		addForm.nickname = '';
		addForm.status = 0;
		addForm.image = '';
		addForm.password = '';
		addRules.password = []
		addRules.password = [{ required: true, message: '请输入密码', trigger: 'blur' }];

	}
	addVisible.value = true;
}
// 删除用户操作
const handleDelete = (row: any) => {
	// 二次确认删除
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		type: 'warning'
	}).then(() => {
		deleteUser({ id: row.id }).then((res: any) => {
			if (res.code !== 200) return ElMessage.error(res.msg || '删除失败')
			ElMessage.success(res.msg || '删除成功！')
			getData();
		})

	})
}
// 页码改变回调
const handlePageChange = (val: number) => {
	query.pageIndex = val;
	getData();
}


// 新增/编辑弹窗相关
const addVisible = ref(false)
const addRef: any = ref()
const addLoading = ref(false)
const addForm = reactive({
	title: '新增',
	id: '',
	username: '',
	password: '',
	status: 0,
	nickname: '',
	image: ''
})
const addRules: FormRules = {
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
	status: [{ required: true, message: '请选择用户等级', trigger: 'blur' }],
	image: [{ required: true, message: '请选择用户头像', trigger: 'blur' }],
};
const closeAdd = (formEl: any) => {
	addVisible.value = false;
}
// 提交表单
const submitAdd = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return ElMessage.error('请正确输入表单信息')
		addLoading.value = true
		if (addForm.title === '新增') {
			const params: any = { ...addForm };
			delete params.title;
			delete params.id;
			addUser(params).then((res: any) => {
				if (res.code !== 200) return ElMessage.error(res.msg || '添加用户失败')
				addVisible.value = false;
				ElMessage.success('添加成功')
				getData();
			}).finally(() => addLoading.value = false)
		} else {
			const params: any = { ...addForm }
			delete params.title;

			updateUser(params).then((res: any) => {
				if (res.code !== 200) return ElMessage.error(res.msg || '更新用户信息失败')
				addVisible.value = false;
				ElMessage.success('更新用户信息成功')
				getData();
			}).finally(() => addLoading.value = false)
		}
	})

}
</script>

<style scoped>
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}

.table {
	width: 100%;
	font-size: 14px;
}

.mr10 {
	margin-right: 10px;
}

.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}

.pagination {
	display: flex;
	justify-content: space-between;
}
</style>